package com.jemmyee.pizza.web.controller;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.DateUtils;
import com.jemmyee.pizza.entity.Buckle;
import com.jemmyee.pizza.entity.Excerpt;
import com.jemmyee.pizza.entity.Surrogate;
import com.jemmyee.pizza.service.IBuckleService;
import com.jemmyee.pizza.service.IExcerptService;
import com.jemmyee.pizza.service.ISurrogateService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.bean.SurrogateBean;
import com.jemmyee.pizza.web.utils.SendMessageUtils;

/**
 * @author qiuchao
 * 2010-12-21
 */
@Controller
@RequestMapping("/admin/surrogate")
public class SurrogateController {
	@Autowired
	private ISurrogateService surrogateService;
	@Autowired
	private IExcerptService excerptService;

	
	
	@RequestMapping("/list/{from}/{startIndex}")
	public ModelAndView list(@PathVariable Integer startIndex,@PathVariable String from,@ModelAttribute SurrogateBean bean,HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Surrogate.class);
		SurrogateBean surrogateBean = new SurrogateBean();
		if (from.equals("form")) {
			surrogateBean = bean;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, surrogateBean);
		}
		if (from.equals("page")) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				surrogateBean = (SurrogateBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
		}
		if (from.equals("menu")) {
			System.out.println("menu is call");
		}

		if(surrogateBean.getName() != null){
			dc.add(Restrictions.like("payPerson", surrogateBean.getName(), MatchMode.ANYWHERE));
		}
		// 发布时间
		if (surrogateBean.getStartTime() != null) {
			dc.add(Restrictions.ge("queryTime", surrogateBean.getStartTime()));
		}
		if (surrogateBean.getEndTime() != null) {
			dc.add(Restrictions.le("queryTime", surrogateBean.getEndTime()));
		}
//		dc.addOrder(Order.desc("queryTime"));
		ModelAndView mv = new ModelAndView();
		Page page = surrogateService.findPageByCriteria(dc,Constants.DEFAULT_PAGESIZE, startIndex,"queryTime");
		
		mv.addObject("page", page);
		mv.addObject("surrogateBean", surrogateBean);
		mv.setViewName("/admin/surrogate/list");
		return mv;
	}
	
	@RequestMapping("/to_up_csv")
	public ModelAndView toUpCsv(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/surrogate/up_csv");
		return mv;
	}
	
	@RequestMapping("/up_csv")
	public ModelAndView upCsv(HttpServletRequest request) throws IOException{
		ModelAndView mv = new ModelAndView();
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;   
		CommonsMultipartFile cmf = (CommonsMultipartFile) multipartRequest.getFile("csvFile");
        if(!cmf.getOriginalFilename().substring(cmf.getOriginalFilename().lastIndexOf(".")+1).equals("csv")){
        	//这个用来处理用户传的文件不是CSV文件时给出错误提示页面
        	mv.setViewName("/admin/surrogate/up_csv");
        	return mv;
        }

    	try {
    		//这个用来跳转成功提示页面
			readCsvToTable(cmf.getInputStream(),request.getParameter("time"));
			mv.setViewName("/admin/surrogate/up_csv");
		} catch (IOException e) {
			e.printStackTrace();
			mv.setViewName("/admin/surrogate/up_csv");
		}

		return mv;
	}
	
	public void readCsvToTable(InputStream ins,String time) throws IOException{
		DataInputStream in = new DataInputStream(ins);
		BufferedReader bufferedreader =  new BufferedReader(new InputStreamReader(in,"GBK"));
		
	    String stemp;   
		
		List<String> lt = new ArrayList<String>();
		while((stemp = bufferedreader.readLine()) != null){  
			for(String s : stemp.split(",")){
				lt.add(s.replace("\"", "").trim());
			}
		}
		System.out.println(lt.size());
		for(int i=22;i<lt.size()&&lt.size()/i>15;i=i+15){
			if(surrogateService.findByProperty("dictateNumber", lt.get(i)) == null || surrogateService.findByProperty("dictateNumber", lt.get(i)).size() == 0){
				Surrogate surrogate = new Surrogate();
				surrogate.setQueryTime(DateUtils.parseStringToDateWithFormat((lt.get(2).substring(0, 4)+"-"+lt.get(2).substring(4, 6)+"-"+lt.get(2).substring(6, 8)+" "+lt.get(2).substring(8)), "yyyy-MM-dd hh:mm:ss"));
				surrogate.setBatchNumber(lt.get(4));
				surrogate.setSurrogateNumber(lt.get(6));
				surrogate.setDictateNumber(lt.get(i));
				surrogate.setPayNumber(lt.get(i+1));
				surrogate.setPayType(lt.get(i+2));
				surrogate.setProtocolNumber(lt.get(i+3));
				surrogate.setMoneyType(lt.get(i+4));
				surrogate.setChargeCard(lt.get(i+5));
				surrogate.setChargeUnit(lt.get(i+6));
				surrogate.setPayCard(lt.get(i+7));
				surrogate.setPayPerson(lt.get(i+8));
				surrogate.setPayMoney(Double.parseDouble(lt.get(i+9)));
				surrogate.setPurpose(lt.get(i+10));
				surrogate.setBankFeedback(lt.get(i+11));
				surrogate.setCustomNumber(lt.get(i+12));
				surrogate.setSendMobile(lt.get(i+13));
				surrogate.setSendFlag(lt.get(i+14));
				surrogateService.save(surrogate);
				
				if(surrogate.getBankFeedback().equals("处理成功")){
					DetachedCriteria dc = DetachedCriteria.forClass(Excerpt.class);
					dc.add(Restrictions.eq("personCard", surrogate.getPayCard()));
					dc.add(Restrictions.eq("personName", surrogate.getPayPerson()));
					dc.add(Restrictions.eq("substr(excerptTime,1,7)", time));
					List<Excerpt> lt_1 = excerptService.findByCriteria(dc);
					if(lt_1 != null && lt_1.size() == 1){
						Excerpt excerpt = new Excerpt();
						excerpt = lt_1.get(0);
						excerpt.setPayStatus(1);
						excerptService.update(excerpt);
					}
				}
			}
		}
		bufferedreader.close();
		in.close();
	}
	
	
}
